import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { View, Text, Button, Input } from '@tarojs/components';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import utils from '@/utils/index';
import './index.scss';

const AddInvoiceHeader = ({ dispatch }) => {
  const [current, setCurrent] = useState(true);
  const [invoiceId, setInvoiceId] = useState();
  const [registration, setRegistration] = useState();
  const [accountNumber, setAccountNumber] = useState();
  const [accountBank, setAccountBank] = useState();
  const [taxNumber, setTaxNumber] = useState();
  const [lookUp, setLookUp] = useState();
  const [ticketSellerMailbox, setTicketSellerMailbox] = useState();
  const [invoHea, setInvoHea] = useState();
  useEffect(() => {
    const parmas = getCurrentInstance().router.params;
    if (parmas.type) {
      const parmasObj = JSON.parse(decodeURI(parmas.jsonObj));
      setInvoiceId(parmasObj.id);
      if (parmasObj.titleType === 2) {
        setInvoHea(parmasObj.title);
        setTicketSellerMailbox(parmasObj.email);
        setCurrent(true);
      } else {
        setRegistration(parmasObj.address);
        setAccountNumber(parmasObj.bankAccount);
        setAccountBank(parmasObj.bankName);
        setTaxNumber(parmasObj.taxpayerNum);
        setLookUp(parmasObj.title);
        setTicketSellerMailbox(parmasObj.email);
        setInvoiceId(parmasObj.id);
        setCurrent(false);
      }
    } else {
      setInvoiceId(null);
    }
  }, [getCurrentInstance().router.params]);
  const inputHandler = (key, e) => {
    switch (key) {
      case 'registration':
        setRegistration(e.detail.value);
        break;
      case 'accountNumber':
        setAccountNumber(e.detail.value);
        break;
      case 'accountBank':
        setAccountBank(e.detail.value);
        break;
      case 'taxNumber':
        setTaxNumber(e.detail.value);
        break;
      case 'lookUp':
        setLookUp(e.detail.value);
        break;
      case 'ticketSellerMailbox':
        setTicketSellerMailbox(e.detail.value);
        break;
      case 'invoHea':
        setInvoHea(e.detail.value);
        break;
    }
  };
  const handleClick = (flag) => {
    setCurrent(flag);
  };
  const submit = () => {
    const re = /^\w+@[a-z0-9]+\.[a-z]{2,4}$/;
    const regTax = /^[a-zA-Z0-9]+$/;
    if (current) {
      if (!invoHea) {
        Taro.showToast({
          title: '请输入公司名称',
          icon: 'none',
        });
        return;
      } else if (ticketSellerMailbox && re.test(ticketSellerMailbox) === false) {
        Taro.showToast({
          title: '请输入正确格式邮箱',
          icon: 'none',
        });
        return;
      }
      if (invoiceId) {
        dispatch({
          type: 'invoiceAssistant/invoiceEditModel',
          payload: {
            einvoiceType: 1,
            title: invoHea,
            id: invoiceId,
            titleType: 2,
            userSource: 'wechat',
            email: ticketSellerMailbox,
          },
        }).then(
          async () => {
            Taro.showToast({
              title: '编辑发票抬头成功',
              icon: 'success',
            });

            await new Promise((resolve) => {
              setTimeout(resolve, 1000);
            });

            utils.backWithRefreash();
          },
          (e) => {
            Taro.showToast({
              title: (e && e.message) || '编辑发票抬头失败',
              icon: 'none',
            });
          },
        );
      } else {
        dispatch({
          type: 'invoiceAssistant/invoiceAddModel',
          payload: {
            einvoiceType: 1,
            title: invoHea,
            titleType: 2,
            userSource: 'wechat',
            email: ticketSellerMailbox,
          },
        }).then(
          async () => {
            Taro.showToast({
              title: '新增发票抬头成功',
              icon: 'success',
            });

            await new Promise((resolve) => {
              setTimeout(resolve, 1000);
            });

            utils.backWithRefreash();
          },
          (e) => {
            Taro.showToast({
              title: (e && e.message) || '新增发票抬头失败',
              icon: 'none',
            });
          },
        );
      }
    } else {
      if (!lookUp) {
        Taro.showToast({
          title: '请输入发票抬头',
          icon: 'none',
        });
        return;
      } else if (!taxNumber || !regTax.test(taxNumber) || taxNumber.length != 18) {
        Taro.showToast({
          title: '请输入有效的税号，由18位数字和字母组成',
          icon: 'none',
        });
        return;
      } else if (ticketSellerMailbox && re.test(ticketSellerMailbox) === false) {
        Taro.showToast({
          title: '请输入正确格式邮箱',
          icon: 'none',
        });
        return;
      }
      if (invoiceId) {
        dispatch({
          type: 'invoiceAssistant/invoiceEditModel',
          payload: {
            id: invoiceId,
            einvoiceType: 1,
            address: registration,
            bankAccount: accountNumber,
            bankName: accountBank,
            taxpayerNum: taxNumber,
            title: lookUp,
            titleType: 1,
            userSource: 'wechat',
            email: ticketSellerMailbox,
            titleType: 1,
          },
        }).then((res) => {
          console.log(res);
          Taro.showToast({
            title: '修改发票抬头成功',
            icon: 'success',
          });
          utils.backWithRefreash();
        });
      } else {
        dispatch({
          type: 'invoiceAssistant/invoiceAddModel',
          payload: {
            einvoiceType: 1,
            address: registration,
            bankAccount: accountNumber,
            bankName: accountBank,
            taxpayerNum: taxNumber,
            title: lookUp,
            titleType: 1,
            userSource: 'wechat',
            email: ticketSellerMailbox,
          },
        }).then((res) => {
          console.log(res);
          Taro.showToast({
            title: '新增发票抬头成功',
            icon: 'success',
          });
          utils.backWithRefreash();
        });
      }
    }
  };
  const personalDom = () => {
    const children = [];
    children.push(
      <View className="bottoInput">
        <Text className="type">发票抬头</Text>
        <Input
          className="code-input"
          value={invoHea}
          onInput={(e) => {
            inputHandler('invoHea', e);
          }}
          placeholder="请输入公司名称（必填）"
          type="text"
        />
      </View>,
    );
    return children;
  };
  const enterpriseDom = () => {
    const children = [];
    children.push(
      <>
        <View className="bottoInput">
          <Text className="type">发票抬头</Text>
          <Input
            className="code-input"
            placeholder="请输入发票抬头（必填）"
            type="text"
            value={lookUp}
            onInput={(e) => {
              inputHandler('lookUp', e);
            }}
          />
        </View>
        <View className="bottoInput">
          <Text className="type">单位税号</Text>
          <Input
            className="code-input"
            placeholder="请输入单位税号（必填）"
            type="text"
            value={taxNumber}
            onInput={(e) => {
              inputHandler('taxNumber', e);
            }}
          />
        </View>
        <View className="bottoInput">
          <Text className="type">注册地址</Text>
          <Input
            className="code-input"
            placeholder="请输入注册地址（选填）"
            type="text"
            value={registration}
            onInput={(e) => {
              inputHandler('registration', e);
            }}
          />
        </View>
        <View className="bottoInput">
          <Text className="type">开户银行</Text>
          <Input
            className="code-input"
            placeholder="请输入开户银行（选填）"
            type="text"
            value={accountBank}
            onInput={(e) => {
              inputHandler('accountBank', e);
            }}
          />
        </View>
        <View className="bottoInput">
          <Text className="type">银行账号</Text>
          <Input
            className="code-input"
            placeholder="请输入银行账号（选填）"
            type="text"
            value={accountNumber}
            onInput={(e) => {
              inputHandler('accountNumber', e);
            }}
          />
        </View>
      </>,
    );
    return children;
  };
  return (
    <View className="addInvoiceHeader">
      <View className="header">
        <View className="inType">
          <Text className="type">发票类型</Text>
          <Text className="electronic customePageBorderStyle customePageStyle">纸质普通发票</Text>
        </View>
      </View>
      <View className="centerCtx">
        <View className="heaText">
          <Text className="type">抬头类型</Text>
        </View>
        <View className="bottonBox">
          <Button
            className={current ? 'btn active customePageBorderStyle customePageStyle' : 'btn'}
            onClick={() => handleClick(true)}
          >
            个人/政府事业单位
          </Button>
          <Button
            style={{ marginTop: 0 }}
            className={!current ? 'btn active customePageBorderStyle customePageStyle' : 'btn'}
            onClick={() => handleClick(false)}
          >
            企业
          </Button>
        </View>
        {current ? personalDom() : enterpriseDom()}
      </View>
      <View className="footer">
        <View className="bottoInput footBI">
          <Text className="type">收票人邮箱</Text>
          <Input
            className="code-input"
            placeholder="请输入邮箱（选填）"
            type="text"
            value={ticketSellerMailbox}
            onInput={(e) => {
              inputHandler('ticketSellerMailbox', e);
            }}
          />
        </View>
        <View className="footerBtn">
          <Button className="btn-blueNew customePageBackgroundStyle" onClick={submit}>
            提交
          </Button>
        </View>
      </View>
    </View>
  );
};
export default connect(({}) => ({}))(AddInvoiceHeader);
